import { rcRequest } from "@core/rc-components/es/RcRequest";
import { getCompanyId } from "@core/shared";
import { getParticipantsFormat } from "./participantsFormat";
import { showConfirm } from "./showConfirm";

/**
 *
 * @param lastItem
 * @param _detailData
 * @param aValue    审批流原有数据
 * @param orderBusType  1 采购方 , 2 销售方
 * @returns
 */
export const getAsyncOriginApproveValue = async (
  lastItem: any = {},
  _detailData: any = {},
  aValue: any[] = [],
  orderBusType = 1
): Promise<any[] | null> => {
  await showConfirm({
    title: "引用原合同审批人",
    content: "确认引用原合同审批人？",
  });
  const detailData = {
    ..._detailData,
    ...lastItem,
  };
  const procInstId =
    detailData?.agreeFlowUnits && detailData?.agreeFlowUnits.length
      ? (detailData?.agreeFlowUnits || [])
          .reverse()
          .find((f) => f.companyId == getCompanyId())?.procInstId
      : detailData?.procInstId;
  //   return value
  const res = await rcRequest<any[]>(
    `/api/activiti/v1/historic-task-instances/${procInstId}/act`
  );
  const signTaskPar = res.find(
    (r) => r.taskName == "电子签章" || r.taskDefKey == "signTask"
  );
  const taskApprovePar = res.find(
    (r) =>
      r.taskName == "审批" ||
      r.taskDefKey == "taskApprove" ||
      r.taskName == "审批人" ||
      r.inputDataItem == "approverList"
  );

  if (taskApprovePar) {
    const newValue = aValue.map((a) => {
      if (a.taskDefKey == "taskApprove" || a.taskName === "审批人") {
        return {
          ...a,
          assignees: (taskApprovePar.participants || []).map(
            getParticipantsFormat(orderBusType)
          ),
        };
      }
      if (
        signTaskPar &&
        (a.taskDefKey == "signTask" || a.taskName === "电子签章")
      ) {
        return {
          ...a,
          assignees: (signTaskPar.participants || []).map(
            getParticipantsFormat(orderBusType)
          ),
        };
      }
      return a;
    });
    return newValue;
  } else {
    return null;
  }
};
